package apiday01.homework;

import java.util.Locale;
import java.util.Random;
import java.util.Scanner;

/*
生成一个4位验证码(数字和字母的组合)，输出到控制台并提示用户输入验证码，输入后若正确则提示验证码
正确，若错误则提示验证码错误。注意：不区分大小写
 */
public class CodeDemo {
    public static void main(String[] args) {
        String strNum = "0123456789";
        String strEng = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        int index;
        //生成一个4位验证码(数字和字母的组合)
        for (int i = 0; i < 3; i++) {
            index = random.nextInt(strEng.length());
            code.append(strEng.charAt(index));
        }
        index = random.nextInt(strNum.length());
        code.insert(random.nextInt(3), strNum.charAt(index));

        int count=5;
        Scanner scanner = new Scanner(System.in);
        //校对用户输入验证码是否正确
       while (count>0) {
            System.out.println("验证码：" + code);
            System.out.println("请输入验证码：");
            String upInput = scanner.nextLine().toUpperCase();
            count--;
            String upCode = code.toString().toUpperCase();
            if (upInput.equals(upCode)) {//equalsIgnoreCase()可直接不区分大小写
                System.out.println("验证码正确");
                break;
            } else {
                System.out.println("验证码错误，还有"+count+"次机会");
            }
        }
       if (count==0){
           System.out.println("连续输入错误5次，请稍后再试");
       }
        scanner.close();
    }
}
